import datetime
import time
import os

# 获取当前时间


dateObj = datetime.datetime.now()

# 保留天数
retentionDays = 3
logsBasePath = f'C:\\Users\\Dapan1\\Desktop\\a\\'
# # basePath = f'/opt/gn_monitor/logs/{dateObj.strftime("%Y-%m")}'
# # path = f'/opt/gn_monitor/logs/{dateObj.strftime("%Y-%m")}'


def handle_expire_log_files(retentionDays, logsBasePath):
    """
    定时删除过期日志文件
    """
    dateObj = datetime.datetime.now()
    path = f'{logsBasePath}/{dateObj.strftime("%Y-%m")}'
    for file_name in os.listdir(path):
        # 判断是否是文件夹
        abs_path = os.path.join(path + file_name)
        if os.path.isfile(abs_path):
            # 判断当前文件日期是否过期
            fileinfo = os.stat(abs_path)
            invalid = int(time.mktime((dateObj - datetime.timedelta(days=retentionDays)).timetuple()))
            # 如果过期则删除
            if fileinfo.st_mtime < invalid:
                os.remove(abs_path)
                print(f"删除成功：{abs_path}")
        else:
            handle_expire_log_files(retentionDays, abs_path)
    for file_name in os.listdir(path):
        # 根据日期判断是否为空文件夹
        abs_path = os.path.join(path + file_name)
        if os.path.isdir(abs_path) and not os.listdir(abs_path):
            os.rmdir(abs_path)


handle_expire_log_files(retentionDays, logsBasePath)